import numpy as np
import cv2
import os

# 创建输出文件夹
output_folder = 'my_bin3'
os.makedirs(output_folder, exist_ok=True)

def img2array(frame):
    """将128x64二值化图像转换为OLED数组格式（8x128字节）"""
    array = np.zeros((8, 128), dtype='uint8')
    for j in range(64):
        for i in range(128):
            if frame[j][i] > 0:
                array[j // 8][i] |= (0x01 << (j % 8))
    return array.flatten()  # 扁平化为1024字节

# 打开视频文件
cap = cv2.VideoCapture('打篮球.mp4')
if not cap.isOpened():
    print("无法打开视频文件")
    exit()

# 获取视频属性
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv2.CAP_PROP_FPS)
ms_per_frame = int(1000 / fps) if fps > 0 else 0

# 创建总信息文件
with open(f'{output_folder}/video_info.txt', 'w') as f_info:
    f_info.write(f'总帧数={total_frames}, 每帧时间={ms_per_frame}ms\n')

# 设置预览窗口
cv2.namedWindow('Preview', cv2.WINDOW_NORMAL)
cv2.resizeWindow('Preview', 128 * 4, 64 * 4)

# 创建输出bin文件
with open(f'{output_folder}/video_frames.bin', 'wb') as f_bin:
    # 逐帧处理
    for frame_idx in range(total_frames):
        ret, img = cap.read()
        if not ret:
            break

        # 图像处理
        img = cv2.resize(img, (128, 64))
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        _, img = cv2.threshold(img, 170, 255, cv2.THRESH_BINARY)

        # 预览处理后的图像
        cv2.imshow('Preview', img)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        # 转换为字节数组
        img_array = img2array(img)

        # 写入帧数据到bin文件
        f_bin.write(img_array.tobytes())

        # 打印进度
        if (frame_idx + 1) % 32 == 0:
            print(f'已处理 {frame_idx + 1} 帧')

# 释放资源
cap.release()
cv2.destroyAllWindows()
print(f"处理完成，数据已保存到 {output_folder}/video_frames.bin 文件中")